import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { DescriptionItemSchema } from '#/components/description';

import { formatDateTime, handleTree } from '@vben/utils';

import { getDeptListCondition } from '#/api/system/dept';
import { getOAuth2ClientList } from '#/api/system/oauth2/client';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'userId',
      label: '操作人',
      component: 'ApiSelect',
      componentProps: {
        api: getSimpleUserList,
        labelField: 'nickname',
        valueField: 'id',
        allowClear: true,
        placeholder: '请选择操作人员',
      },
    },
    {
      fieldName: 'type',
      label: '操作模块',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入操作模块',
      },
    },
    {
      fieldName: 'subType',
      label: '操作名',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入操作名',
      },
    },
    {
      fieldName: 'action',
      label: '操作内容',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入操作内容',
      },
    },
    {
      fieldName: 'clientId',
      label: '应用名称',
      component: 'ApiSelect',
      componentProps: {
        api: getOAuth2ClientList,
        labelField: 'name',
        valueField: 'clientId',
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
    },
    {
      fieldName: 'unitId',
      label: '单位',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['areaCode'],
        componentProps: (values) => {
          return {
            // 关键：用 areaCode 作为 key，强制重新渲染
            key: values.areaCode || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'unit',
                ...(values.areaCode ? { areaCode: values.areaCode } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择单位',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('unitId', undefined);
        },
      },
    },
    {
      fieldName: 'deptId',
      label: '归属部门',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['unitId'],
        componentProps: (values) => {
          return {
            // 关键：用 unitId 作为 key，强制重新渲染
            key: values.unitId || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'dept',
                ...(values.unitId ? { unitId: values.unitId } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择归属部门',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('deptId', undefined);
        },
      },
    },
    {
      fieldName: 'createTime',
      label: '操作时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
    {
      fieldName: 'bizId',
      label: '业务编号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入业务编号',
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      field: 'id',
      title: '日志编号',
      minWidth: 100,
    },
    {
      field: 'userName',
      title: '操作人',
      minWidth: 120,
    },
    {
      field: 'type',
      title: '操作模块',
      minWidth: 120,
    },
    {
      field: 'subType',
      title: '操作名',
      minWidth: 160,
    },
    {
      field: 'action',
      title: '操作内容',
      minWidth: 200,
    },
    {
      field: 'createTime',
      title: '操作时间',
      minWidth: 180,
      formatter: 'formatDateTime',
    },
    {
      field: 'bizId',
      title: '业务编号',
      minWidth: 120,
    },
    {
      field: 'userIp',
      title: '操作 IP',
      minWidth: 120,
    },
    {
      field: 'operateCategoryName',
      title: '业务类型',
      minWidth: 200,
    },
    {
      field: 'areaName',
      title: '所属区域',
      minWidth: 120,
    },
    {
      field: 'unitName',
      title: '所属单位',
      minWidth: 120,
    },
    {
      field: 'deptName',
      title: '所属部门',
      minWidth: 120,
    },
    {
      field: 'appName',
      title: '所属应用',
      minWidth: 120,
    },
    {
      title: '操作',
      width: 80,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      field: 'id',
      label: '日志编号',
    },
    {
      field: 'traceId',
      label: '链路追踪',
      show: (data) => !data?.traceId,
    },
    {
      field: 'userId',
      label: '操作人编号',
    },
    {
      field: 'userName',
      label: '操作人名字',
    },
    {
      field: 'userIp',
      label: '操作人 IP',
    },
    {
      field: 'userAgent',
      label: '操作人 UA',
    },
    {
      field: 'type',
      label: '操作模块',
    },
    {
      field: 'subType',
      label: '操作名',
    },
    {
      field: 'action',
      label: '操作内容',
    },
    {
      field: 'operateCategoryName',
      label: '业务类型',
    },
    {
      field: 'areaName',
      label: '所属区域',
    },
    {
      field: 'unitName',
      label: '所属单位',
    },
    {
      field: 'deptName',
      label: '所属部门',
    },
    {
      field: 'appName',
      label: '所属应用',
    },
    {
      field: 'extra',
      label: '操作拓展参数',
      show: (val) => !val,
    },
    {
      field: 'requestUrl',
      label: '请求 URL',
      render: (val, data) => {
        if (data?.requestMethod && val) {
          return `${data.requestMethod} ${val}`;
        }
        return '';
      },
    },
    {
      field: 'createTime',
      label: '操作时间',
      render: (val) => formatDateTime(val) as string,
    },
    {
      field: 'bizId',
      label: '业务编号',
    },
  ];
}
